package powernode.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.powernode.domain.SysLog;
import com.powernode.util.AuthUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description: 系统日志切面
 * @Author: Tong Ziyu
 * @Date: 2025/2/5 11:41
 */
//@Aspect
//@Component
@Slf4j
public class SysLogAspect {

    public static final String POINT_CUT = "execution(* com.powernode.controller.*.*(..))";

    @Around(value = POINT_CUT)
    public Object logAround(ProceedingJoinPoint pjp){
        Object result = null;

        SysLog sysLog = new SysLog();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        // 获取ip
        String remoteHost = request.getRemoteHost();

        // 获取参数
        Object[] args = pjp.getArgs();

        String argsStr = "";
        // 判断 如果上传的是文件,则将标注情况
        if (ObjectUtil.isNotNull(args) && args.length != 0 && args[0] instanceof MultipartFile){
            argsStr = "文件";
        }else{
            argsStr = JSONObject.toJSONString(args);
        }



        // 获取方法名
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        Method method = methodSignature.getMethod();
        String methodName = method.getName();

        // 获取用户名
        Long loginUserId = AuthUtil.getLoginUserId();

        // 取目标方法上的注解的value值
        String operationValue = "";
        ApiOperation declaredAnnotation = method.getDeclaredAnnotation(ApiOperation.class);
        if (ObjectUtils.isNotNull(declaredAnnotation)){
            operationValue = declaredAnnotation.value();
        }
        // 记录开始时间
        long start = System.currentTimeMillis();
        // 执行方法
        try {
            result = pjp.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }


        // 记录结束时间
        long end = System.currentTimeMillis();

        sysLog.setUserId(loginUserId);
        sysLog.setParams(argsStr);
        sysLog.setIp(remoteHost);
        sysLog.setCreateDate(new Date());
        sysLog.setOperation(operationValue);
        sysLog.setMethod(methodName);
        sysLog.setTime(end - start);

        log.info("日志记录成功:{}",sysLog);

        // 插入数据库中


        return result;
    }
}
